ASP.NET MVC Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET MVC Model Binding

Back to: ASP.NET MVC Tutorial

In ASP.NET MVC, model binding refers to the process where incoming HTTP request data is automatically mapped to parameters in an action method or a model object. This allows you to handle form submissions, query string parameters, and route data by simply defining parameters in your action methods or by binding them to a model.

How Model Binding Works

  1. HTTP Request: Data comes from various sources like form fields (POST), query strings (GET), or route data.
  2. Model Binder: The model binder automatically maps the data from the request to action method parameters or model properties.
  3. Action Method Execution: The action method executes using the data populated by the model binder.

Data Sources for Model Binding

  • Form Data: Data submitted via forms.
  • Query Strings: Parameters in the URL.
  • Route Data: Values defined in the URL pattern (in RouteConfig).
  • Custom Value Providers: You can create your own value provider for specialized sources.

Model Binding Example

Let’s take a simple example where we have a form that submits Name and Age to a controller.

Step 1: Create a Model

Create a class to represent the data structure (the model).

csharp
public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}

 

Step 2: Create a View with a Form

We create a form in a view that submits the data.

html
@model YourNamespace.Models.Person
@using (Html.BeginForm("SubmitPerson", "Home", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Name)
@Html.TextBoxFor(m => m.Age)
 
}
  • @Html.TextBoxFor(m => m.Name) generates the input field for Name and binds it to the Name property of the Person model.
  • Similarly, the Age input is bound to the Age property.

 

Step 3: Create a Controller Action

In the controller, you create an action method to handle the submitted data.

csharp
 public class HomeController : Controller
{
[HttpPost]
public ActionResult SubmitPerson(Person person)
{
if (ModelState.IsValid)
{
// Do something with the person object
return RedirectToAction("PersonDetails", person);
}
return View();
}
public ActionResult PersonDetails(Person person)
{
  return View(person);
 }
}
  • The SubmitPerson action method takes a Person object as a parameter. ASP.NET MVC automatically binds the form data to this model.
  • ModelState.IsValid checks if the model binding was successful and if any validation rules have been violated.
  • After processing, you can pass the model to another view or return a response.

Step 4: Create a View to Display Submitted Data

Create a view called PersonDetails.cshtml to display the data.

html
@model YourNamespace.Models.Person
Person Details
Name: @Model.Name

Age: @Model.Age
Model Binding from Query Strings or Route Data

Besides form data, model binding can also bind from query strings or route parameters.

Query String Example

If the URL is /Home/SubmitPerson?name=John&age=25, you can bind the query string parameters directly to the model:

csharp
public ActionResult SubmitPerson(string name, int age)
{
 var person = new Person { Name = name, Age = age };
 return View(person);
}

Route Data Example

You can also configure route data in RouteConfig:

csharp
routes.MapRoute
(
name: "Default", url: "{controller}/{action}/{name}/{age}",
defaults: new { controller = "Home", action = "SubmitPerson", name = UrlParameter.Optional, age = UrlParameter.Optional }
);

Now if you visit /Home/SubmitPerson/John/25, it will bind the values to the name and age parameters in the action.

csharp
 public ActionResult SubmitPerson(string name, int age)
 {
 var person = new Person { Name = name, Age = age };
 return View(person);
 }

 

Custom Model Binder

In some cases, you might want to implement a custom model binder if the default binder does not fit your requirements.

Custom Model Binder Example

csharp
 public class CustomPersonBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request; string name = request.Form.Get("Name");
int age = Convert.ToInt32(request.Form.Get("Age"));
return new Person { Name = name, Age = age };
}
}

 

To register this custom binder:


csharp
csharp
ModelBinders.Binders.Add(typeof(Person), new CustomPersonBinder());

Summary

  • Model binding simplifies the process of transferring data from HTTP requests into C# objects.
  • ASP.NET MVC provides default model binders for common scenarios.
  • You can bind data from form inputs, query strings, and route parameters.
  • You can create custom model binders for more complex scenarios.

Model binding is crucial for handling user input efficiently and securely in MVC applications.

Scroll to Top